package com.zmn.oms.api.controller.third.tc58;

import com.alibaba.fastjson.JSON;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.common.constant.TodmConsts;
import com.zmn.oms.common.enums.ChannelFacade;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.RequestUtil;
import com.zmn.oms.third.base.dto.api.ApiInvokResult;
import com.zmn.oms.third.core.tracker.FacadeTracker;
import com.zmn.oms.third.daowei.DaoweiConsts;
import com.zmn.oms.third.tc58.Tc58Consts;
import com.zmn.oms.third.tc58.dto.Tc58Response;
import com.zmn.oms.third.tc58.dto.api.Tc58Order;
import com.zmn.oms.third.tc58.dto.api.Tc58OrderStatus;
import com.zmn.oms.third.tc58.dto.api.Tc58SecondPayInfo;
import com.zmn.oms.third.tc58.dto.api.Tc58ServiceTime;
import com.zmn.oms.third.tc58.service.Tc58Service;
import com.zmn.oms.third.tc58.util.Tc58Util;
import com.zmn.oms.third.todm.Todm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 类描述：58同城Vip对外接口
 *  用于接收58同城Vip向我方的订单推送及订单状态变更推送
 *
 * @author LiangHailong
 * @date 2019/09/24 23:25
 */
@RestController
@RequestMapping("/steward")
@Slf4j
public class Tc58VipController {
    @Autowired
    private Tc58Service tc58Service;

    /**
     * 接收订单推送消息（添加订单）
     */
    @PostMapping("/order/syncorder")
    @ResponseBody
    public Tc58Response addOrder(HttpServletRequest request) {
        String paramsStr = RequestUtil.getPostParameter(request);
        log.info("【{}】收到新单消息！ Body:[{}]", Tc58Consts.CHANNEL_NAME, paramsStr);

        FacadeTracker.FacadeTrackerCore tracker = FacadeTracker.getTracker()
                .dataIn(ChannelFacade.TONGCHENG_58)
                .remark("收到新单消息")
                .reqSummary(paramsStr);

        Tc58Response result = null;

        ApiInvokResult<Tc58Order> params = Tc58Util.parseRequest(paramsStr, Tc58Order.class);
        if (params.isSuccess()) {
            try {
                tc58Service.saveOrder(params.getData());
                result = result(true, "成功");
            } catch (OmsBaseException oe) {
                log.error(oe.getMessage(), oe);
                result = result(false, "失败:"+ oe.getMessage());
                tracker.error(oe, "录单失败：%s", oe.getMessage());
            } catch (Exception e) {
                log.error(String.valueOf(e.getMessage()), e);
                result = result(false, "失败");
                tracker.error(e, "系统异常，录单失败");
            }
        }
        else {
            result = result(false, params.getMsg());
        }

        tracker.respSummary(JSON.toJSONString(result))
                .success(result.getCode() == 0)
                .commit();

        return result;
    }

    @ResponseBody
    @GetMapping("/test/findOrderDetail")
    public String findOrderDetail(HttpServletRequest request) {
        String orderIdStr = request.getParameter("orderId");
        String sign = request.getParameter("sign");
        log.info("【{}】收到手动调用58精选订单详情！ orderId:[{}], sign:[{}]", Tc58Consts.CHANNEL_NAME, orderIdStr, sign);

        if (StringUtil.isBlank(orderIdStr) || StringUtil.isBlank(sign) ) {
            return "参数不全！";
        }
        if (!"zmnTest666666".equals(sign)) {
            return "Who are you????";
        }

        try {
            Long orderId = Long.parseLong(orderIdStr);

            String phone = tc58Service.activeJingxuanOrder(orderId);
            return "执行成功：手机号："+ phone;
        } catch (OmsBaseException e) {
            return "执行报错："+ e.getMessage();
        }
    }

    /**
     * 接收订单状态变更消息（修改订单状态）
     */
    @PostMapping("/order/syncstate")
    @ResponseBody
    public Tc58Response changeOrderStatus(HttpServletRequest request) {
        String paramsStr = RequestUtil.getPostParameter(request);
        log.info("【{}】收到状态变更消息！ Body:[{}]", Tc58Consts.CHANNEL_NAME, paramsStr);

        FacadeTracker.FacadeTrackerCore tracker = FacadeTracker.getTracker()
                .dataIn(ChannelFacade.TONGCHENG_58)
                .remark("收到状态变更消息")
                .reqSummary(paramsStr);

        Tc58Response result = null;

        ApiInvokResult<Tc58OrderStatus> params = Tc58Util.parseRequest(paramsStr, Tc58OrderStatus.class);
        if (params.isSuccess()) {
            try {
                tc58Service.changeOrderStatus(params.getData());
                result = result(true, "成功");
            } catch (Exception e) {
                log.error(String.valueOf(e.getMessage()), e);
                result = result(false, "失败");
                tracker.error(e, "系统异常，订单状态变更失败");
            }
        }
        else {
            result = result(false, params.getMsg());
        }

        tracker.respSummary(JSON.toJSONString(result))
                .success(result.getCode() == 0)
                .commit();

        return result;
    }

    /**
     * 接收订单二段支付信息消息
     */
    @PostMapping("/order/secondpayinfo")
    @ResponseBody
    public Tc58Response secondPayInfo(HttpServletRequest request) {
        String paramsStr = RequestUtil.getPostParameter(request);
        log.info("【{}】收到订单二段支付消息！ Body:[{}]", Tc58Consts.CHANNEL_NAME, paramsStr);

        FacadeTracker.FacadeTrackerCore tracker = FacadeTracker.getTracker()
                .dataIn(ChannelFacade.TONGCHENG_58)
                .remark("收到订单二段支付消息")
                .reqSummary(paramsStr);

        Tc58Response result = null;

        ApiInvokResult<Tc58SecondPayInfo> params = Tc58Util.parseRequest(paramsStr, Tc58SecondPayInfo.class);
        if (params.isSuccess()) {
            try {
                tc58Service.saveSecondPayInfo(params.getData());
                result = result(true, "成功");
            } catch (Exception e) {
                log.error(String.valueOf(e.getMessage()), e);
                result = result(false, "失败");
                tracker.error(e, "系统异常，订单二段支付失败");
            }
        }
        else {
            result = result(false, params.getMsg());
        }

        tracker.respSummary(JSON.toJSONString(result))
                .success(result.getCode() == 0)
                .commit();

        return result;
    }

    /**
     * 接收修改预约时间消息
     */
    @PostMapping("/order/syncservicetime")
    @ResponseBody
    public Tc58Response syncServiceTime(HttpServletRequest request) {
        String paramsStr = RequestUtil.getPostParameter(request);
        log.info("【{}】收到修改预约时间消息！ Body:[{}]", Tc58Consts.CHANNEL_NAME, paramsStr);

        FacadeTracker.FacadeTrackerCore tracker = FacadeTracker.getTracker()
                .dataIn(ChannelFacade.TONGCHENG_58)
                .remark("收到修改预约时间消息")
                .reqSummary(paramsStr);

        Tc58Response result = null;

        ApiInvokResult<Tc58ServiceTime> params = Tc58Util.parseRequest(paramsStr, Tc58ServiceTime.class);
        if (params.isSuccess()) {
            try {
                tc58Service.changeServiceTime(params.getData());
                result = result(true, "成功");
            } catch (OmsBaseException oe) {
                log.error(oe.getMessage(), oe);
                result = result(false, "失败："+ oe.getMessage());
                tracker.error(oe, "修改预约时间失败：%s", oe.getMessage());
            } catch (Exception e) {
                log.error(String.valueOf(e.getMessage()), e);
                result = result(false, "失败");
                tracker.error(e, "系统异常，修改预约时间失败");
            }
        }
        else {
            result = result(false, params.getMsg());
        }

        tracker.respSummary(JSON.toJSONString(result))
                .success(result.getCode() == 0)
                .commit();

        return result;
    }

    /**
     * 生成返回结果
     * @param isSuccess
     * @param message
     * @return
     */
    private Tc58Response result(boolean isSuccess, String message) {
        Tc58Response result = new Tc58Response();
        result.setResult(isSuccess);
        result.setCode(isSuccess ? 0 : 1);
        result.setMessage(message);

        result.setSign(Tc58Util.sign(result));

        return result;
    }

}
